package cn.xuqiudong.backend.base.controller;

import cn.xuqiudong.common.base.model.BaseResponse;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2025-03-10 10:44
 */
//@Controller
public class CustomErrorController implements ErrorController {

    // 注入默认的 ErrorAttributes，用于获取错误详细信息
    private final ErrorAttributes errorAttributes;

    public CustomErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    /**
     * 处理 /error 请求，返回自定义 JSON 错误信息
     */
    @RequestMapping("/error")
    @ResponseBody
    public BaseResponse<?> handleError(HttpServletRequest request) {
        System.out.println("1233  into CustomErrorController");
        // 使用 ServletWebRequest 包装 HttpServletRequest
        ServletWebRequest webRequest = new ServletWebRequest(request);

        // 获取错误属性，ErrorAttributeOptions 可以自定义获取哪些错误信息
        Map<String, Object> errorAttributesMap = this.errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults());

        // 提取 HTTP 状态码
        int status = (int) errorAttributesMap.getOrDefault("status", 500);
        String message = (String) errorAttributesMap.getOrDefault("error", "Error");
        Object detail = errorAttributesMap.getOrDefault("message", "");
        return BaseResponse.error(status, message).setData(detail);
    }
}